//
//  MXLockViewController.m
//  MXLoginMethodsDomo
//
//  Created by 马彦 on 16/9/27.
//  Copyright © 2016年 MX. All rights reserved.
//
/**
 *
 *      密码解锁控制器
 *
 */

#import "MXLockViewController.h"
#import "MXLockConfig.h"
#import "MXLockIndicator.h"
#import "MXLockSudoko.h"
#import "MXLockPassword.h"

#import "MXPromptView.h"

typedef NS_ENUM(NSInteger, MXLockStep)
{
    MXLockStepNone = 0,
    MXLockStepCreateNew,
    MXLockStepCreateAgain,
    MXLockStepCreateNotMatch,  //不匹配
    MXLockStepCreateReNew,   //更新
    MXLockStepModifyOld,
    MXLockStepModifyOldError,
    MXLockStepModifyReOld,
    MXLockStepModifyNew,
    MXLockStepModifyAgain,
    MXLockStepModifyNotMatch,
    MXLockStepModifyReNew,
    MXLockStepVerifyOld,
    MXLockStepVerifyOldError,
    MXLockStepVerifyReOld,
    MXLockStepRemoveOld,
    MXLockStepRemoveOldError,
    MXLockStepRemoveReOld
};

@interface MXLockViewController ()<MXLockSudokoDelegate>

/**小图*/
@property (nonatomic, strong) MXLockIndicator *indicator;
/**大图*/
@property (nonatomic, strong) MXLockSudoko *sudoko;
/**提示语*/
@property (nonatomic, weak) UILabel *noticeLbl;
/**重置按钮*/
@property (nonatomic, weak) UIButton *resetBtn;

@property (nonatomic, assign) MXLockStep step;

@property (nonatomic, strong) NSString *passwordTemp;

@end

@implementation MXLockViewController

- (instancetype)initWithType:(MXLockType)type appearMode:(MXLockAppearMode)appearMode {
    if (self = [super init]) {
        self.type = type;
        self.appearMode = appearMode;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setup];
    [self initGui];
    
    [self swithWithType:self.type];
}


- (void)setup {
    self.title = @"创建手势密码";
    self.view.backgroundColor = MXLOCK_COLOR_BACKGROUND;
    _step = MXLockStepNone;
}

- (void)initGui {
    
    self.indicator = [[MXLockIndicator alloc] init];
    [self.view addSubview:self.indicator];
    
    UILabel *noticeLbl = [[UILabel alloc] init];
    noticeLbl.textAlignment = NSTextAlignmentCenter;
    noticeLbl.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:noticeLbl];
    self.noticeLbl = noticeLbl;

    self.sudoko = [[MXLockSudoko alloc] init];
    self.sudoko.delegate = self;
    [self.view addSubview:self.sudoko];
    
    UIButton *resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    resetBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [resetBtn setTitleColor:MXLOCK_COLOR_RESET forState:UIControlStateNormal];
    [resetBtn setTitle:MXLOCK_RESET_TEXT forState:UIControlStateNormal];
    [resetBtn addTarget:self action:@selector(resetBtnOnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:resetBtn];
    self.resetBtn = resetBtn;
    
}

/**重置按钮响应方法*/
- (void)resetBtnOnAction {
    if (self.type == MXLockTypeCreate) {
        [self updateGuiForStep:MXLockStepCreateNew];
    } else if (self.type == MXLockTypeModify) {
        [self updateGuiForStep:MXLockStepModifyNew];
    }
}

- (void)swithWithType:(MXLockType)type {
    switch (type) {
        case MXLockTypeCreate:
            [self updateGuiForStep:MXLockStepCreateNew];
            break;
        case MXLockTypeModify:
            [self updateGuiForStep:MXLockStepModifyOld];
            break;
        case MXLockTypeVerify:
            [self updateGuiForStep:MXLockStepVerifyOld];
            break;
        case MXLockTypeRemove:
            [self updateGuiForStep:MXLockStepRemoveOld];
            break;
        default:
            break;
    }
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self layoutSubview];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self layoutSubview];
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [self layoutSubview];
}

/**
 适配
 */
- (void)layoutSubview {
    [self.indicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.bottom.mas_equalTo(self.noticeLbl.mas_top).offset(-20);
        make.width.mas_equalTo(MXLOCOR_INDICATOR_SIDE_LENGTH);
        make.height.mas_equalTo(MXLOCOR_INDICATOR_SIDE_LENGTH);
    }];
    
    [self.noticeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(14);
        make.bottom.mas_equalTo(self.sudoko.mas_top).offset(-20);
    }];
    [self.sudoko mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.width.and.height.mas_equalTo(MXLOCK_SUDOKO_SIDE_LENGTH);
    }];
    [self.resetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(MXLOCK_RESET_BTN_HEIGHT);
        make.top.mas_equalTo(self.sudoko.mas_bottom).offset(50);
    }];
}



- (void)updateGuiForStep:(MXLockStep)step {
    _step = step;
    
    switch (step) {
        case MXLockStepCreateNew:{
            self.noticeLbl.text = MXLOCK_NEW_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepCreateAgain:{
            self.noticeLbl.text = MXLOCK_AGAIN_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = NO;
            self.resetBtn.hidden = NO;
        }
            break;
        case MXLockStepCreateNotMatch:{
            self.noticeLbl.text = MXLOCK_NOT_MATCH_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_ERROR;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepCreateReNew:{
            self.noticeLbl.text = MXLOCK_RE_NEW_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepModifyOld:{
            self.noticeLbl.text = MXLOCK_OLD_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepModifyOldError:{
            self.noticeLbl.text = MXLOCK_OLD_ERROR_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_ERROR;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepModifyReOld:{
            self.noticeLbl.text = MXLOCK_RE_OLD_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepModifyNew:{
            self.noticeLbl.text = MXLOCK_NEW_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepModifyAgain:{
            self.noticeLbl.text = MXLOCK_AGAIN_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = NO;
            self.resetBtn.hidden = NO;
        }
            break;
        case MXLockStepModifyNotMatch:{
            self.noticeLbl.text = MXLOCK_NOT_MATCH_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_ERROR;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepModifyReNew:{
            self.noticeLbl.text = MXLOCK_RE_NEW_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepVerifyOld:{
            self.noticeLbl.text = MXLOCK_OLD_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepVerifyOldError:{
            self.noticeLbl.text = MXLOCK_OLD_ERROR_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_ERROR;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepVerifyReOld:{
            self.noticeLbl.text = MXLOCK_RE_OLD_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepRemoveOld:{
            self.noticeLbl.text = MXLOCK_OLD_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepRemoveOldError:{
            self.noticeLbl.text = MXLOCK_OLD_ERROR_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_ERROR;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        case MXLockStepRemoveReOld:{
            self.noticeLbl.text = MXLOCK_RE_OLD_TEXT;
            self.noticeLbl.textColor = MXLOCK_COLOR_NORMAL;
            
            self.indicator.hidden = YES;
            self.resetBtn.hidden = YES;
        }
            break;
        default:
            break;
    }
}

- (void)shakeAnimationForView:(UIView *)view {
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 10, position.y);
    CGPoint right = CGPointMake(position.x + 10, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES];
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    
    [viewLayer addAnimation:animation forKey:nil];
}

- (void)hide {
    switch (self.appearMode) {
        case MXLockAppearModePush: {
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        case MXLockAppearModePresent: {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}


#pragma makr - MXLockSudokoDelegate 

- (void)sudoko:(MXLockSudoko *)sudoko passwordDidCireate:(NSString *)password {
    switch (self.step) {
            
        case MXLockStepCreateNew:
        case MXLockStepCreateReNew: {
            if (password.length < 4) { //创建新密码
                MXPromptView *promptView = [[MXPromptView alloc] init];

                [promptView promptViewAlertViewWithView:self.view Title:@"连接点最少四个,请重新绘制"];
                
                return ;
            }
            self.passwordTemp = password;
           
            [self updateGuiForStep:MXLockStepCreateAgain];
        }
            break;
        case MXLockStepCreateAgain: { //再次输入新密码
            if ([password isEqualToString:self.passwordTemp]) {
                [MXLockPassword setNewPassword:password];
                
                if ([self.delegate respondsToSelector:@selector(passwordDidCreate:)]) {
                    [self.delegate passwordDidCreate:password];
                }
                
                [self hide];
            } else {
                [self updateGuiForStep:MXLockStepCreateNotMatch];
                [self.sudoko showErrorPassword:password];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self updateGuiForStep:MXLockStepCreateReNew];
                });
            }
            
        }
            break;
        case MXLockStepModifyOld:
        case MXLockStepModifyReOld: { //修改密码
            
            if ([password isEqualToString:[MXLockPassword oldPassword]]) {
                [self updateGuiForStep:MXLockStepModifyNew];
            } else {
                [self updateGuiForStep:MXLockStepModifyOldError];
                [self.sudoko showErrorPassword:password];
                [self shakeAnimationForView:self.noticeLbl];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self updateGuiForStep:MXLockStepModifyOld];
                });
            }
        }
            break;
        case MXLockStepModifyNew:
        case MXLockStepModifyReNew: { //修改的新密码
            self.passwordTemp = password;
            if (password.length < 4) { //创建新密码
                MXPromptView *promptView = [[MXPromptView alloc] init];
                
                [promptView promptViewAlertViewWithView:self.view Title:@"连接点最少四个,请重新绘制"];
                
                return ;
            }
            
            [self updateGuiForStep:MXLockStepModifyAgain];
        }
            break;
        case MXLockStepModifyAgain: { //再次去人修改的新密码
            if ([password isEqualToString:self.passwordTemp]) {
                [MXLockPassword setNewPassword:password];
                
                if ([self.delegate respondsToSelector:@selector(passwordDidModify:)]) {
                    [self.delegate passwordDidModify:password];
                }
                [self hide];
            } else {
                [self updateGuiForStep:MXLockStepModifyNotMatch];
                [self.sudoko showErrorPassword:password];
                [self shakeAnimationForView:self.noticeLbl];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self updateGuiForStep:MXLockStepModifyReNew];
                });
            }
        }
            break;
        case MXLockStepVerifyOld:
        case MXLockStepVerifyReOld: {
            if ([password isEqualToString:[MXLockPassword oldPassword]]) {
                if ([self.delegate respondsToSelector:@selector(passwordDidVerify:)]) {
                    [self.delegate passwordDidVerify:password];
                }
                [self hide];
            } else {
                [self updateGuiForStep:MXLockStepVerifyOldError];
                [self.sudoko showErrorPassword:password];
                [self shakeAnimationForView:self.noticeLbl];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self updateGuiForStep:MXLockStepVerifyReOld];
                });
            }
        }
            break;
        case MXLockStepRemoveOld:
        case MXLockStepRemoveReOld: { //移除密码
            if ([password isEqualToString:[MXLockPassword oldPassword]]) {
                [MXLockPassword removePassword];
                if ([self.delegate respondsToSelector:@selector(passwordDidRemove)]) {
                    [self.delegate passwordDidRemove];
                }
                [self hide];
            } else {
                [self updateGuiForStep:MXLockStepRemoveOldError];
                [self.sudoko showErrorPassword:password];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self updateGuiForStep:MXLockStepRemoveReOld];
                });
            }
            
        }
            break;
        default:
            break;
    }
    [self.indicator showPassword:password];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
